//
//  SRClassDetailViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/20.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRClassDetailViewController.h"

#import "SRSchoolClassServices.h"
#import "SRClassMemberCollectionViewCell.h"
#import "SRClassMemberListViewController.h"

#import <FZCommonShare.h>


@interface SRClassDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>


@property (weak, nonatomic) IBOutlet UIView *infoView;

@property (weak, nonatomic) IBOutlet UILabel *schoolNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *classNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *codeLabel;

@property (strong, nonatomic) UICollectionView          *collectionView;
@property (strong, nonatomic) UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) NSMutableArray            *items;
@property (assign, nonatomic) NSInteger                 start;

@property (weak, nonatomic) IBOutlet UIView *memberHeaderView;
@property (strong, nonatomic) UIButton *rightButton;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet UIButton *morelistButton;

@end

@implementation SRClassDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view
    self.title = @"班级详情";
    [self setupData];
    [self setupCollectionView];
    
    [self setupNavigationItem];
    
    ESWeakSelf;
    self.loadingView.clickButtonBlock = ^(id sender){
        ESStrongSelf;
        [_self queryData];
    };
    
    if (self.userType == SRSchoolClassUserTypeStudent) {
        [self.morelistButton setTitle:@"更多" forState:UIControlStateNormal];
    }
    
    [self showLoadingViewWithCompletedBlock:nil];
//    [self queryData];
    [self queryClassDetail];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

#pragma mark - Init UI

- (void)setupData {
    self.items = [NSMutableArray arrayWithCapacity:0];
    self.start = 0;
}

-(void)setupCollectionView
{
        //    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    CGFloat itemSpace = 6;
    CGFloat cellWidth = floorf((SCREEN_WIDTH - itemSpace) / 6.f) - 1;
    CGFloat cellHeight = cellWidth + 45;
    
    flowLayout.itemSize = CGSizeMake(cellWidth, cellHeight);
    flowLayout.minimumLineSpacing = itemSpace;
    flowLayout.minimumInteritemSpacing = itemSpace;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, itemSpace, 0, itemSpace);
    
    self.flowLayout = flowLayout;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    [self.collectionView registerNib:[UINib nibWithNibName:kSRClassMemberCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kSRClassMemberCollectionViewCell];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
//    self.collectionView.alwaysBounceVertical = YES;
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [FZStyleSheet currentStyleSheet].color_2;
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.top.equalTo(self.memberHeaderView.mas_bottom);
    }];
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.schoolNameLabel.textColor = self.classNameLabel.textColor = self.codeLabel.textColor = [UIColor colorWithHex:0x4e4033];
    self.schoolNameLabel.font = self.classNameLabel.font = self.codeLabel.font = css.fontOfH5;

}

- (void)setupNavigationItem {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 80, 40);
    [rightButton setTitle:@"邀请加入" forState:UIControlStateNormal];
    rightButton.titleLabel.font = css.fontOfH5;
    
    self.rightButton = rightButton;
    [rightButton addTarget:self action:@selector(onRightButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    [self setRightBarButtonItem:rightItem];
}

#pragma mark - Event

- (void)onRightButton:(id)sender {
    WEAKSELF
    FZCommonShareContent *shareContent = [[FZCommonShareContent alloc] init];
    shareContent.dataType = FZCommonShareContentTypeWebpage;
//    NSString *nickname = [SRLoginUser nickname];
        //    NSString *bookName = @"";
    shareContent.title = [NSString stringWithFormat:@"快来加入我的班级：%@，跟我一起作业吧", self.model.name];
    shareContent.desc = @"专为小学生设计的智能学习机";
    UIImage *image = [UIImage imageNamed:@"appLogo"];
    shareContent.thumbnailData = UIImagePNGRepresentation(image);
    
    shareContent.webpageUrl = self.model.shareURL;
    
    [[FZCommonShare sharedInstance] shareFromViewController:self content:shareContent fullCompletion:^(FZCommonShareSocialSNSType socialType, FZCommonShareResponseState responseState, NSString *errorMessage) {
        if (responseState == FZCommonShareResponseStateSuccess) {
            [weakSelf showHUDHintWithText:@"分享成功"];
        } else if (responseState == FZCommonShareResponseStateNotInstalled) {
            [weakSelf showHUDHintWithText:[NSString stringWithFormat:@"您的手机不支持分享到该APP"]];
        }
    }];

}

- (IBAction)onCopyButton:(id)sender {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.model.inviteCode;
    [self showHUDHintWithText:@"已复制"];
}
- (IBAction)onListButton:(id)sender {
    
    SRClassMemberListViewController *vc = [[SRClassMemberListViewController alloc] init];
    vc.userType = self.userType;
    vc.classModel = self.model;
    
    WEAKSELF
    vc.DeleteStudentSuccessBlock = ^(NSArray *uids) {
        
        STRONGSELFFor(weakSelf)
        [strongSelf queryData];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)updateHeaderView {
    self.schoolNameLabel.text = [NSString stringWithFormat:@"学校名称：%@", self.model.schoolName];
    self.classNameLabel.text = [NSString stringWithFormat:@"班级名称：%@", self.model.name];
    self.codeLabel.text = [NSString stringWithFormat:@"班级邀请码：%@", self.model.inviteCode];
    
    self.countLabel.text = [NSString stringWithFormat:@"班级学员（%ld）", (long)self.model.currentNum];


}

#pragma mark - Query Data

- (void)queryClassDetail {
    WEAKSELF
    [SRSchoolClassServices queryClassDetailGroupID:self.groupID successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf hideLoadingView];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            weakSelf.model = responseDataObject;
            [weakSelf updateHeaderView];
            
            [weakSelf queryData];
        } else {
            [weakSelf failedLoadingViewWithTitle:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf hideLoadingView];
        [weakSelf failedLoadingViewWithTitle:nil];
    }];
}

- (void)queryData{
    self.start = 0;
    [self queryListData:NO];
}


- (void)queryListData:(BOOL)isRefresh {
    WEAKSELF
    
    [SRSchoolClassServices queryClassMemberListPage:self.start groupID:self.groupID successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        
//        [weakSelf hideLoadingView];
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            if (!isRefresh || weakSelf.start == 0) {
                [weakSelf.items removeAllObjects];
            }
            NSArray *addItems = responseDataObject;
            NSInteger addCount = [addItems count];
            weakSelf.start += addCount;
            
            if (addCount > 0) {
                [weakSelf.items addObjectsFromArray:addItems];
            }

            [weakSelf.collectionView reloadData];
            
        } else {
            [weakSelf showHUDError];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        
//        [weakSelf.collectionView.header endRefreshing];
//        [weakSelf.collectionView.footer endRefreshing];
        [weakSelf showHUDError];
        if (!isRefresh) {
//            [weakSelf.loadingView failed];
        }
    }];
    
}

#pragma mark - UICollectionDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  [self.items count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SRClassMemberCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSRClassMemberCollectionViewCell forIndexPath:indexPath];
    
    SRClassMemberItemModel *model = self.items[indexPath.item];
    [cell updateCellInfo:model];

    return cell;
}

#pragma mark - UICollectionDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        //    FZHomeCourseModel *model = self.items[indexPath.item];
    
}


@end
